package de.isibboi.cassandraintro;

import java.util.Arrays;

import me.prettyprint.cassandra.service.ThriftKsDef;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
import me.prettyprint.hector.api.factory.HFactory;

/**
 * Utility class for communicating with Cassandra.
 * 
 * @author Sebastian Schmidt
 * 
 */
public class CassandraUtil {
	public static final String KEYSPACE = "testspace";
	public static final String COLUMN_FAMILY = "testfamily";
	public static final String CLUSTER = "testcluster";

	private CassandraUtil() {
	}

	/**
	 * Returns the keyspace with the given name. If it doesn't exist, it is
	 * created.
	 * 
	 * @return The keyspace with the given name.
	 */
	public static Keyspace getKeyspace(String keyspaceName, String columnFamilyName) {
		Cluster cluster = HFactory.getOrCreateCluster("testcluster", "localhost:9160");

		KeyspaceDefinition keyspaceDef = cluster.describeKeyspace(keyspaceName);

		if (keyspaceDef == null) {
			ColumnFamilyDefinition columnFamily = HFactory.createColumnFamilyDefinition(keyspaceName, columnFamilyName,
					ComparatorType.UTF8TYPE);
			keyspaceDef = HFactory.createKeyspaceDefinition(keyspaceName, ThriftKsDef.DEF_STRATEGY_CLASS, 1,
					Arrays.asList(columnFamily));
			cluster.addKeyspace(keyspaceDef);
		}

		return HFactory.createKeyspace(keyspaceName, cluster);
	}
}